package com.ruoyi.biz.controller;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.biz.domain.*;
import com.ruoyi.biz.mapper.BizGameTagMapper;
import com.ruoyi.biz.pojo.dto.BizGameDTO;
import com.ruoyi.biz.pojo.dto.BizGameQueryDTO;
import com.ruoyi.biz.pojo.vo.BizGameDetailVO;
import com.ruoyi.biz.pojo.vo.BizGameVO;
import com.ruoyi.biz.service.*;
import com.ruoyi.biz.util.MySecurityUtil;
import com.ruoyi.biz.util.SizeParser;
import com.ruoyi.common.utils.IpUtils;
import com.ruoyi.common.utils.LogUtils;
import com.ruoyi.common.utils.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 游戏信息Controller
 *
 * @author jason
 * @date 2025-10-31
 */
@Controller
@RequestMapping("/biz/game")
public class BizGameController extends BaseController {
    private String prefix = "biz/game";

    @Autowired
    private IBizGameService bizGameService;

    @Autowired
    BizGameTagMapper bizGameTagMapper;

    @Autowired
    IBizTagService tagService;

    @Autowired
    IBizFileService fileService;

    @Autowired
    IBizGameTagService gameTagService;

    @Value("${cover}")
    String coverUrl;

    @Value("${website.domain}")
    private String domain;



    @RequiresPermissions("biz:game:view")
    @GetMapping()
    public String game() {
        return prefix + "/game";
    }


    @RequiresPermissions("biz:game:view")
    @GetMapping("/toTree")
    public String toTagTree(@RequestParam(value = "gameId", required = false) String gameId, ModelMap mmap) {
        mmap.put("gameId", StringUtils.isEmpty(gameId) ? "0" : gameId);
        return prefix + "/tree";
    }

    /**
     * 查询游戏信息列表
     */
    @RequiresPermissions("biz:game:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BizGame bizGame) {
        startPage();
        List<BizGame> list = bizGameService.selectBizGameList(bizGame);


        return getDataTable(list);
    }

    /**
     * 查询游戏信息列表
     */
    @PostMapping("/listPage")
    @ResponseBody
    public PageInfo<BizGameVO> listPage(@RequestBody BizGameQueryDTO param) {

        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<BizGame> list = bizGameService.listBizGame(param);

        // 先包装成 PageInfo（保留分页元数据）
        PageInfo<BizGame> pageInfo = new PageInfo<>(list);
        // 转换数据内容为 VO
        List<BizGameVO> voList = pageInfo.getList().stream().map(bizGame -> {
            BizGameVO vo = BeanUtil.copyProperties(bizGame, BizGameVO.class);
            if (bizGame.getCreateTime() != null) {
                vo.setCreateTime(DateUtil.format(bizGame.getCreateTime(), "yyyy年MM月dd日"));
            }
            if (bizGame.getUpdateTime() != null) {
                vo.setUpdateTime(DateUtil.format(bizGame.getUpdateTime(), "yyyy年MM月dd日"));
            }
            // 查询标签
            BizGameTag query = new BizGameTag();
            query.setGameId(bizGame.getId());
            List<BizGameTag> gameTags = gameTagService.selectBizGameTagList(query);
            if (CollUtil.isNotEmpty(gameTags)) {
                Set<Long> collect = gameTags.stream().map(BizGameTag::getTid).collect(Collectors.toSet());
                List<BizTag> tags = tagService.listByIds(collect);
                vo.setTags(StrUtil.join(" ,", tags.stream().map(BizTag::getName).collect(Collectors.toSet())));
            }
            // 查询封面
            BizFile queryFile = new BizFile();
            queryFile.setGameId(bizGame.getId());
            queryFile.setFace("1");
            List<BizFile> files = fileService.selectBizFileList(queryFile);
            if (CollUtil.isNotEmpty(files)) {
                BizFile bizFile = files.get(0);
                if (!bizFile.getLink().startsWith("http")) {
                    String allPath = domain + bizFile.getLink();
                    vo.setCover(allPath);
                } else {
                    vo.setCover(bizFile.getLink());
                }
            } else {
                // 没有设置封面，取默认的
                vo.setCover(coverUrl);
            }

            // 对提取码进行加密
            vo.setPassword(MySecurityUtil.encode(vo.getPassword()));
            LogUtils.getAccessLog().info("【附件地址】{}", vo.getCover());
            return vo;
        }).collect(Collectors.toList());

        // 手动构造新的 PageInfo<BizGameVO>，但保留原来的分页信息
        PageInfo<BizGameVO> result = new PageInfo<>();
        result.setList(voList);
        result.setTotal(pageInfo.getTotal());
        result.setPageNum(pageInfo.getPageNum());
        result.setPageSize(pageInfo.getPageSize());
        result.setPages(pageInfo.getPages());
        result.setSize(pageInfo.getSize());
        result.setPrePage(pageInfo.getPrePage());
        result.setNextPage(pageInfo.getNextPage());

        return result;
    }

    private static final Set<String> VIDEO_EXTENSIONS = new HashSet<>(Arrays.asList(
            "mp4", "avi", "mov", "wmv", "flv", "mkv", "webm", "mpeg", "mpg", "3gp", "m4v", "ts"
    ));

    @Autowired
    IBizPanService bizPanService;

    @GetMapping("/detail/{id}")
    @ResponseBody
    public BizGameDetailVO selectOne(@PathVariable("id") Long id) {
        BizGame bizGame = bizGameService.selectBizGameById(id);
        if (bizGame == null) {
            return null;
        }
        BizGameDetailVO vo = BeanUtil.copyProperties(bizGame, BizGameDetailVO.class);
        if (bizGame.getCreateTime() != null) {
            vo.setCreateTime(DateUtil.format(bizGame.getCreateTime(), "yyyy年MM月dd日"));
        }
        if (bizGame.getUpdateTime() != null) {
            vo.setUpdateTime(DateUtil.format(bizGame.getUpdateTime(), "yyyy年MM月dd日"));
        }
        // 查询标签
        BizGameTag query = new BizGameTag();
        query.setGameId(bizGame.getId());
        List<BizGameTag> gameTags = gameTagService.selectBizGameTagList(query);
        if (CollUtil.isNotEmpty(gameTags)) {
            Set<Long> collect = gameTags.stream().map(BizGameTag::getTid).collect(Collectors.toSet());
            List<BizTag> tags = tagService.listByIds(collect);
            vo.setTags(StrUtil.join(" ,", tags.stream().map(BizTag::getName).collect(Collectors.toSet())));
        }
        // 查询封面
        BizFile queryFile = new BizFile();
        queryFile.setGameId(bizGame.getId());
        List<BizFile> files = fileService.selectBizFileList(queryFile);
        if (CollUtil.isNotEmpty(files)) {

            List<String> allImages = new ArrayList<>();
            for (BizFile file : files) {
                // 首图
                if (Objects.equals(file.getFace(), "1")) {
                    vo.setCover(getRealUrl(file.getLink()));
                }
                // 视频
                if (Objects.equals(file.getType(), "0") && VIDEO_EXTENSIONS.contains(file.getFileType())) {
                    vo.setAvi(getRealUrl(file.getLink()));
                    continue;
                }
                // 所有图片
                allImages.add(getRealUrl(file.getLink()));
            }

            BizPan queryPan = new BizPan();
            queryPan.setGameId(id);
            List<BizPan> bizPans = bizPanService.selectBizPanList(queryPan);
            if (CollUtil.isNotEmpty(bizPans)) {
                List<Map<String, String>> list = new ArrayList<>();
                for (BizPan bizPan : bizPans) {
                    Map<String, String> map = new HashMap<>();
                    map.put("PanName", bizPan.getName());
                    map.put("PanLink", bizPan.getLink());
                    list.add(map);
                }

                vo.setPans(list);
            }

            vo.setImgs(allImages);
        } else {
            // 没有设置封面，取默认的
            vo.setCover(coverUrl);
        }

        return vo;
    }



    private String getRealUrl(String str) {
        if (StrUtil.isNotBlank(str) && !str.startsWith("http")) {
            return domain + str;
        } else {
            return str;
        }
    }


    /**
     * 查询游戏信息列表
     */
    @RequiresPermissions("biz:game:list")
    @GetMapping("/select")
    @ResponseBody
    public List<BizGame> selectList() {
        return bizGameService.selectBizGameList(new BizGame());
    }

    /**
     * 导出游戏信息列表
     */
    @RequiresPermissions("biz:game:export")
    @Log(title = "游戏信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(BizGame bizGame) {
        List<BizGame> list = bizGameService.selectBizGameList(bizGame);
        ExcelUtil<BizGame> util = new ExcelUtil<BizGame>(BizGame.class);
        return util.exportExcel(list, "游戏信息数据");
    }

    /**
     * 新增游戏信息
     */
    @RequiresPermissions("biz:game:add")
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存游戏信息
     */
    @RequiresPermissions("biz:game:add")
    @Log(title = "游戏信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(BizGameDTO bizGame) {
        bizGame.setBytes(SizeParser.parseSizeToBytes(bizGame.getSize()));
        return toAjax(bizGameService.insertBizGame(bizGame));
    }

    /**
     * 修改游戏信息
     */
    @RequiresPermissions("biz:game:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        BizGame bizGame = bizGameService.selectBizGameById(id);
        // 读取标签

        String joinNames = StringUtils.EMPTY;
        BizGameTag param = new BizGameTag();
        param.setGameId(bizGame.getId());
        List<BizGameTag> gameTags = bizGameTagMapper.selectBizGameTagList(param);
        if (!CollectionUtils.isEmpty(gameTags)) {
            Set<Long> collect = gameTags.stream().map(BizGameTag::getTid).collect(Collectors.toSet());
            joinNames = tagService.listByIds(collect).stream().map(BizTag::getName).collect(Collectors.joining(","));
        }
        mmap.put("tags", joinNames);
        mmap.put("bizGame", bizGame);
        return prefix + "/edit";
    }

    /**
     * 修改保存游戏信息
     */
    @RequiresPermissions("biz:game:edit")
    @Log(title = "游戏信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(BizGameDTO bizGame) {
        return toAjax(bizGameService.updateBizGame(bizGame));
    }

    /**
     * 删除游戏信息
     */
    @RequiresPermissions("biz:game:remove")
    @Log(title = "游戏信息", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(bizGameService.deleteBizGameByIds(ids));
    }
}
